package com.utils; /**
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @author ceshi
 * @date 2018/7/189:43
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.apache.commons.lang.time.StopWatch;

/**
 * @Author: Liudongyang
 * @Description:
 * @Date: Created in 9:43 2018/7/18
 * @Modified By:
 * @Version: 1.0.0
 */
@Aspect
public class TimerCount {

  Log log = LogFactory.getLog(this.getClass());

  /**
   * Pointcut 定义Pointcut，Pointcut名称为aspectjMethod,必须无参，无返回值 只是一个标识，并不进行调用
   */
  @Pointcut("execution(* *(..)) && !execution(* main(..))")
  private void aspectJMethod() {
  }

  ;

  //  @Before("aspectJMethod()")
  public void doBefore(JoinPoint joinPoint) {
  }

  @Around("aspectJMethod()")
  public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    //核心逻辑
    StopWatch clock = new StopWatch();
    clock.start(); // 计时开始
    Object retVal = pjp.proceed();
    clock.stop(); // 计时结束
    log.info(pjp.getSignature().getName() + "方法所用时间:" + clock.getTime() / 1000.000 + "s");
    return retVal;
  }

  //  @After(value = "aspectJMethod()")
  public void doAfter(JoinPoint joinPoint) {
  }

  @AfterReturning(value = "aspectJMethod()", returning = "retval")
  public void doReturn(JoinPoint joinPoint, String retval) {
    System.out.println("AfterReturning()开始");
    System.out.println("Return value= " + retval);
    System.out.println("此处可对返回结果做一些处理");
    System.out.println("----AfterReturning()结束----");
  }

  @AfterThrowing(value = "aspectJMethod()", throwing = "e")
  public void doThrowing(JoinPoint joinPoint, Exception e) {
    System.out.println("-----doThrowing()开始-----");
    System.out.println(" 错误信息：" + e.getMessage());
    System.out.println(" 此处意在执行核心业务逻辑出错时，捕获异常，并可做一些日志记录操作等等");
    System.out.println(" 可通过joinPoint来获取所需要的内容");
    System.out.println("-----End of doThrowing()------");
  }


}
